//
//  JackImageCacher.m
//  JackToolsBox
//
//  Created by Jack Xue on 2019/12/3.
//  Copyright © 2019 Jack Xue. All rights reserved.
//

#import "JackImageCacher.h"
#import "JKImageDiskCache.h"    //硬盘缓存管理者
/*
 内存 + 硬盘 的多级缓存
 JKImageDiskCache中管理硬盘缓存
 */
@interface JackImageCacher(){
    NSCache *_memCache;            //内存缓存
}
@end

@implementation JackImageCacher
- (instancetype)init
{
    self = [super init];
    if (self) {
        NSLog(@"生成缓存");
        _memCache = [NSCache new];
    }
    return self;
}

#pragma mark - 查询图片缓存
///匹配缓存
-(UIImage*)checkImageCacheWithKey:(NSString*)key{
    UIImage *result = nil;
    if ([_memCache objectForKey:key]) {
        //内存命中
//        NSLog(@"内存命中");
        result = (UIImage*)[_memCache objectForKey:key];
        return result;
    }
    result = [JKImageDiskCache searchImageInDiskWithKey:key];
    if (result){
        //硬盘命中
//        NSLog(@"硬盘命中");
        //将图片加入到内存中，流畅性高但是内存并没有过多消耗
        [_memCache setObject:result forKey:key];
        return result;
    }
    return result;
}

#pragma mark - 将图片缓存
-(void)addImageToCacheWithKey:(NSString*)key image:(UIImage*)image{
    //image保存在内存中
    [_memCache setObject:image forKey:key];
    
    //image保存在硬盘中
    dispatch_queue_t diskCacheQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(diskCacheQueue, ^{
        [JKImageDiskCache addImageToDisk:image withKey:key];
    });
}

#pragma mark - 移除缓存
-(void)removeAllImageFromCache{
    //清除所有内存中缓存的图片
    [_memCache removeAllObjects];
    
    //清除所有硬盘中缓存的图片
    [JKImageDiskCache removeImageFromDisk];
}

@end
